
<template>
  <div>
    <!-- <el-card id="table-head-block">
      <b>个人数据</b>
    </el-card> -->
    <!-- <p>{{chosenDate}}</p> -->
    <el-card id="table-block">
      <div class="block">
        <el-row>
          <el-col :span="12">
            <el-cascader placeholder="搜索部门/人物"
                         v-model="user"
                         :options="options4depart"
                         @change="userChange"
                         filterable></el-cascader>
          </el-col>
          <el-col :span="12">
            <el-select v-model="checkOpt"
                       placeholder="查询日期类型">
              <el-option v-for="item in options"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
        <br />
        <span class="demonstration">选择日期</span>
        <el-date-picker v-if='checkOpt == "false"'
                        v-model="chosenDate"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd"
                        @change="sendRequest"
                        :picker-options="pickerOptions4Week">
        </el-date-picker>
        <el-date-picker v-else
                        v-model="chosenDate"
                        type="monthrange"
                        align="right"
                        unlink-panels
                        range-separator="至"
                        start-placeholder="开始月份"
                        end-placeholder="结束月份"
                        value-format="yyyy-MM"
                        @change="sendRequest"
                        :picker-options="pickerOptions4Month">
        </el-date-picker>
        <br />
        <br />
        <wt-button type="primary"
                   plain
                   round
                   @click="exportExcel">点击导出<i class="el-icon-download el-icon--right"></i></wt-button>
        <wt-button type="primary"
                   plain
                   round
                   @click="showCharts = true">数据分析<i class="el-icon-s-data el-icon--right"></i></wt-button>
      </div>
      <el-table id="table"
                :data="tableData"
                style="width: 100%">
        <el-table-column prop="activities"
                         label="项目"
                         width="150"
                         fixed
                         align="center">
        </el-table-column>
        <el-table-column v-if='checkOpt == "true"'
                         :label="today"
                         align="center">
          <el-table-column v-for="(item, index) in colLabel"
                           :key="index"
                           :label="item">
            <template slot-scope="scope">
              <span v-if="scope.row.effort"
                    style="margin-left: 10px">{{ scope.row.effort[index] }}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column v-else
                         :label="today"
                         align="center">
          <el-table-column v-for="(item, index) in colLabel"
                           :key="index"
                           :label="item">
            <template slot-scope="scope">
              <span v-if="scope.row.effort"
                    style="margin-left: 10px">{{ scope.row.effort[index] }}</span>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </el-card>
    <charts v-if="showCharts"
            :tableData="statisticData"
            :flag="flag"
            @closedialog="showCharts = false" />
  </div>

</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
import charts from "@/components/charts";
import WtButton from "@/components/Button";
import dateInfo from "../utils/dateInfo";

export default {
  components: {
    charts,
    WtButton
  },
  data() {
    return {
      flag: 1,
      showCharts: false,
      options: [
        {
          value: "true",
          label: "按月查询"
        },
        {
          value: "false",
          label: "按周查询"
        }
      ],
      checkOpt: "false", //false 按月, true 按周
      today: "",
      chosenDate: "",
      colLabel: [],
      colNum: "",
      tableData: [
        {
          activities: "",
          efforts: []
        }
      ],
      statisticData: [
        {
          activities: "",
          efforts: []
        }
      ],
      pickerOptions4Week: {
        firstDayOfWeek: 1,
        shortcuts: [
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      pickerOptions4Month: {
        shortcuts: [
          {
            text: "本月",
            onClick(picker) {
              picker.$emit("pick", [new Date(), new Date()]);
            }
          },
          {
            text: "今年至今",
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().getFullYear(), 0);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近六个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      options4depart: [
        {
          value: "",
          label: "",
          children: [
            {
              value: "",
              label: ""
            }
          ]
        }
      ],
      user: ""
    };
  },
  methods: {
    // *用户
    userChange(user) {
      // console.log('user:', user)
      if (user.length == 2) {
        this.user = user[1];
      } else {
        this.user = user[0];
      }

      this.flushDate();
      if (
        this.user &&
        this.checkOpt &&
        this.chosenDate[0] &&
        this.chosenDate[1]
      ) {
        this.$api.userInfo
          .requestIndividualData({
            UserId: this.user,
            isMonth: this.checkOpt,
            startTime: this.chosenDate[0],
            endTime: this.chosenDate[1]
          })
          .then(response => {
            // console.log("表单内容", response.data);
            this.tableData = [];
            this.statisticData = [];
            for (var i = 0; i < response.data.ProjectNames.length; i++) {
              this.tableData.push({
                activities: response.data.ProjectNames[i],
                effort: response.data.efforts[i]
              });
              this.statisticData.push({
                activities: response.data.ProjectNames[i],
                effort: response.data.efforts[i]
              });
            }
            // console.log("表单内容后来", this.tableData);
          })
          .catch(error => {
            console.log("error: ", error);
          });
      }
    },

    // *发送查询请求
    sendRequest() {
      this.flushDate();
      // console.log("sendRequest参数",this.user, this.checkOpt, this.chosenDate[0], this.chosenDate[1]);
      if (
        this.user &&
        this.checkOpt &&
        this.chosenDate[0] &&
        this.chosenDate[1]
      ) {
        this.$api.userInfo
          .requestIndividualData({
            UserId: this.user,
            isMonth: this.checkOpt,
            startTime: this.chosenDate[0],
            endTime: this.chosenDate[1]
          })
          .then(response => {
            // console.log("表单内容", response.data);
            this.tableData = [];
            this.statisticData = [];

            let effortSum = [];
            for (let j = 0; j < response.data.efforts[0].length; j++) {
              effortSum[j] = 0;
            }
            //工时数据推入
            for (var i = 0; i < response.data.ProjectNames.length; i++) {
              this.tableData.push({
                activities: response.data.ProjectNames[i],
                effort: response.data.efforts[i]
              });
              this.statisticData.push({
                activities: response.data.ProjectNames[i],
                effort: response.data.efforts[i]
              });
              // 按列求和
              if (response.data.efforts[0].length) {
                for (let j = 0; j < response.data.efforts[0].length; j++) {
                  effortSum[j] += response.data.efforts[i][j];
                }
              }
            }
            this.tableData.push({
              activities: "Summary",
              effort: effortSum
            });
          })
          .catch(error => {
            console.log("error: ", error);
          });
      }
    },
    // *刷新表头时间
    flushDate() {
      var temp = [];
      if (!this.chosenDate[0] || !this.chosenDate[1]) {
        return;
      }
      if (this.checkOpt == "false") {
        //周的时间列表处理
        // console.log("按月处理,不需要处理后的时间", this.chosenDate);
        let yearDiff =
          parseInt(this.chosenDate[1].split("-")[0]) -
          parseInt(this.chosenDate[0].split("-")[0]);
        var begin = parseInt(dateInfo.getWeekNum(this.chosenDate[0]));
        var end = parseInt(dateInfo.getWeekNum(this.chosenDate[1]));
        if (yearDiff >= 1) {
          var t = 0;
          for (i = 0; i <= yearDiff; i++) {
            // Math.floor(parseInt(this.NumDates((new Date(this.chosenDate[1])).getFullYear() + i))/7);
            let weekNum = dateInfo.getweekNums(
              new Date(this.chosenDate[0]).getFullYear() + i
            );
            if (i == 0) {
              for (var j = begin; j <= weekNum; j++) {
                temp[t++] =
                  "第" + (j % weekNum == 0 ? weekNum : j % weekNum) + "周";
              }
            } else if (i == yearDiff) {
              for (var j = 1; j <= end; j++) {
                temp[t++] =
                  "第" + (j % weekNum == 0 ? weekNum : j % weekNum) + "周";
              }
            } else {
              for (var j = 1; j <= weekNum; j++) {
                temp[t++] = "第" + j + "周";
              }
            }
          }
        } else {
          let weekNum = dateInfo.getweekNums(
            new Date(this.chosenDate[0]).getFullYear()
          );
          this.colNum = end - begin + 1;
          for (var j = 0; j < this.colNum; j++) {
            temp[j] =
              "第" +
              (parseInt(begin % weekNum) == 0 ? weekNum : begin % weekNum) +
              "周";
            begin++;
          }
        }
      } else {
        // 月的时间列表处理
        this.chosenDate[0] = this.chosenDate[0] + "-" + "01";
        this.chosenDate[1] =
          this.chosenDate[1] +
          "-" +
          dateInfo.getMonthDaysNum(
            this.chosenDate[1].split("-")[0],
            this.chosenDate[1].split("-")[1]
          );
        // console.log("按月处理,处理后的时间", this.chosenDate);
        if (
          this.chosenDate[0].split("-")[0] == this.chosenDate[1].split("-")[0]
        ) {
          var begin = parseInt(this.chosenDate[0].split("-")[1]);
          var end = parseInt(this.chosenDate[1].split("-")[1]);
          this.colNum = end - begin + 1;
          for (var i = begin; i <= end; i++) {
            temp[i - begin] = i + "月";
          }
        } else {
          // 如果年数不同
          var begin = parseInt(this.chosenDate[0].split("-")[1]);
          var end =
            12 *
              parseInt(
                this.chosenDate[1].split("-")[0] -
                  this.chosenDate[0].split("-")[0]
              ) +
            parseInt(this.chosenDate[1].split("-")[1]);
          // console.log(begin, end);
          this.colNum = end - begin + 1;
          var k = 0;
          for (var i = begin; i <= end; i++) {
            if (i <= 12) {
              temp[i - begin] = i + "月";
            } else {
              temp[i - begin] = i - 12 * parseInt(k / 12 + 1) + "月";
              ++k;
            }
          }
        }
      }
      this.colLabel = temp;
    },
    // *定义导出Excel表格事件
    exportExcel: function() {
      /* 从表生成工作簿对象 */
      var wb = XLSX.utils.table_to_book(document.querySelector("#table"));
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          "项目数据.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") {
          console.log(e, wbout);
        }
      }
      return wbout;
    }
  },
  created: function() {
    // var today = new Date();
    // // this.today = today;
    // console.log("today: ", today);
    // this.today =
    //     today.getFullYear() +
    //     "-" +
    //     (today.getMonth() + 1) +
    //     "-" +
    //     today.getDate();
  },
  mounted: function() {
    this.$api.userInfo
      .requestUsers()
      .then(response => {
        // console.log("收到的部门/人物", response.data);
        var temp = [];
        for (var i = 0; i <= response.data.length; i++) {
          if (i == 0) {
            temp[0] = {
              value: "全部",
              label: "全部"
            };
          } else {
            temp[i] = {
              value: response.data[i - 1].department,
              label: response.data[i - 1].department,
              children: []
            };
            for (var j = 0; j < response.data[i - 1].username.length; j++) {
              temp[i].children[j] = {
                value: response.data[i - 1].userid[j],
                label: response.data[i - 1].username[j]
              };
            }
          }
        }
        this.options4depart = temp;
        // console.log("复制后收到的部门/人物", this.options4depart);
      })
      .catch(error => {
        console.log("error: ", error);
      });
  }
  // computed: function() {}
};
</script>


<style lang="less" scoped>
.block {
  margin-bottom: 30px;
  margin-top: 25px;
}
#table-block {
  width: 85%;
  margin: 50px auto;
  border-radius: 25px;
  padding: 0px 10px;
}
#table-head-block {
  width: 200px;
  font-size: 20px;
  margin: 20px auto;
  border-radius: 25px;
}
</style>
